package ru.arriah.servicedesk.web.chief.action;

import java.io.IOException;
import java.text.DateFormat;
import java.util.Date;
import java.util.Locale;

import javax.naming.NamingException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import ru.arriah.common.web.action.ActionMapping;
import ru.arriah.common.web.action.DumbAction;
import ru.arriah.servicedesk.bean.ReportBean;
import ru.arriah.servicedesk.ejb.RequestManagerLocalHome;
import ru.arriah.servicedesk.ejb.RequestManagerLocalObject;
import ru.arriah.servicedesk.help.Utils;
import ru.arriah.servicedesk.web.commonaction.exception.InternalException;

public class DisplayReports extends DumbAction {
   protected RequestManagerLocalHome requestManagerHome;
   
   public DisplayReports() throws NamingException {
      super();

      requestManagerHome = 
         Utils.getRequestManagerHomeInterface();         
   }

   public String execute(
      ActionMapping actionMapping,
      HttpServletRequest request,
      HttpServletResponse response
   ) throws IOException, ServletException {
     try {
       
       Date startDate = null;
       Date endDate = null;
       
       DateFormat dateformat = 
          DateFormat.getDateInstance(
             DateFormat.SHORT, 
             new Locale("ru")
          );

       try {
         startDate = 
           dateformat.parse(request.getParameter("startDate"));
       } catch (Exception e) {
         startDate = new Date();
       }
       
       try {
         endDate = 
           dateformat.parse(request.getParameter("endDate"));
       } catch (Exception e) {
         endDate = new Date();
       }
       
       RequestManagerLocalObject requestManager = 
         requestManagerHome.create();                                               
                                                    
       ReportBean reportBean = 
         requestManager.selectReport(startDate, endDate);
       
       requestManager.remove();
       
       request.setAttribute("startDate", startDate);
       request.setAttribute("endDate", endDate);
       request.setAttribute("report", reportBean);
       
       return actionMapping.getSuccessTarget();
    } catch (Exception e) {
       handleException(e, "execute");
       throw new InternalException("ErrorMessage.internal");
    }
   }
}